﻿using System;
using System.Drawing;
using System.IO;
using System.Windows.Forms;
using Emgu.CV;
using Emgu.CV.Structure;

namespace CCDTest
{
    public partial class Form2 : Form
    {
        PicPositionInfo templatePicObj;
        public Image<Bgr, byte> template; // 用來存儲加載的圖片
        private Rectangle _selectionRect; // 用來存儲選擇區域
        private bool _isSelecting; // 記錄是否正在選擇區域
        private float _scaleX = 1.0f; // 圖像在X方向上的縮放比例
        private float _scaleY = 1.0f; // 圖像在Y方向上的縮放比例
        public delegate void TemplateSavedHandler(PicPositionInfo picPositionInfo);
        public event TemplateSavedHandler TemplateSaved;

        public Form2(PicPositionInfo _templatePicObj)
        {
            InitializeComponent();
            templatePicObj = _templatePicObj;
        }

        // 開始選擇區域
        private void pictureBox_MouseDown(object sender, MouseEventArgs e)
        {
            if (template != null)
            {
                _isSelecting = true;

                // 計算相對於圖片的起始位置
                float originalX = e.X;
                float originalY = e.Y;

                // 設置框選區域的起始點，這些是圖像原始大小中的座標
                _selectionRect = new Rectangle((int)originalX, (int)originalY, 0, 0);
            }
        }

        // 更新選擇區域
        private void pictureBox_MouseMove(object sender, MouseEventArgs e)
        {
            if (_isSelecting && template != null)
            {
                // 不需要考虑缩放比例，直接使用相对pictureBox的坐标
                float originalX = e.X;
                float originalY = e.Y;

                // 更新选择区域的大小
                _selectionRect.Width = (int)(originalX - _selectionRect.X);
                _selectionRect.Height = (int)(originalY - _selectionRect.Y);

                pictureBox.Invalidate(); // 使畫布重繪
            }
        }

        // 結束選擇區域
        private void pictureBox_MouseUp(object sender, MouseEventArgs e)
        {
            _isSelecting = false;
            if (_selectionRect.Width > 0 && _selectionRect.Height > 0)
            {
                // 計算所選區域的原始圖像坐標
                PicPositionInfo picPositionInfo = new PicPositionInfo()
                { 
                    X = (int)(_selectionRect.X * _scaleX),
                    Y = (int)(_selectionRect.Y * _scaleY),
                    Width = (int)(_selectionRect.Width * _scaleX),
                    Height = (int)(_selectionRect.Height * _scaleY)
                };

                // 根据原始坐标截取图片
                var selectedRegion = template.Copy(new Rectangle(
                   picPositionInfo.X,
                   picPositionInfo.Y,
                   picPositionInfo.Width,
                   picPositionInfo.Height
                ));

                // 彈出對話框詢問是否保存
                DialogResult result = MessageBox.Show("是否要保存为模板?", "提示", MessageBoxButtons.YesNo);
                if (result == DialogResult.Yes)
                {
                    string directoryPath = Path.Combine(Application.StartupPath, "Template");
                    if (!Directory.Exists(directoryPath))
                    {
                        Directory.CreateDirectory(directoryPath);
                    }

                    string filePath = Path.Combine(directoryPath, Guid.NewGuid().ToString() + ".jpg");
                    selectedRegion.Save(filePath);
                    MessageBox.Show("保存成功!");

                    // 触发事件并将保存路径传回Form1
                    picPositionInfo.fileName = filePath;
                    TemplateSaved?.Invoke(picPositionInfo);
                }
            }
        }

        // 顯示選擇區域
        private void pictureBox_Paint(object sender, PaintEventArgs e)
        {
            if (template != null)
            {
                // 畫出選擇框
                using (Pen pen = new Pen(Color.Red, 2))
                {
                    e.Graphics.DrawRectangle(pen, _selectionRect);
                }
            }
        }

        private void Form2_Load(object sender, EventArgs e)
        {
            pictureBox.Image?.Dispose();
            pictureBox.Image = templatePicObj.pictureBox.Image;
            template = new Image<Bgr, byte>(templatePicObj.fileName);

            // 計算縮放比例
            _scaleX = (float)template.Width / pictureBox.Width;
            _scaleY = (float)template.Height / pictureBox.Height;
        }
    }
}
